/*
 * UmsgMediaCasterConnection.h
 *
 *  Created on: 2016年7月15日
 *      Author: terry
 */

#ifndef UMSGMEDIACASTERCONNECTION_H_
#define UMSGMEDIACASTERCONNECTION_H_

#include "MediaStream.h"
#include "MediaTransport.h"
#include "TByteBuffer.h"
#include <json/json.h>
#include <udt.h>
#include "TThread.h"
#include "MediaPacketQueue.h"
#include "UdtSocketPair.h"


namespace av
{

class UmsgMediaCasterServer;

class UmsgMediaCasterConnection : public av::MediaSink,
								 public comn::Thread,
								 public std::enable_shared_from_this< UmsgMediaCasterConnection >
{
public:
	UmsgMediaCasterConnection();
	virtual ~UmsgMediaCasterConnection();

    bool equals(const std::string& name) const;

	bool open(UmsgMediaCasterServer* server, UDTSOCKET fd);
	void close();


    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);

    UDTSOCKET getHandle();

    const std::string& getStreamName();

    const sockaddr_in& getPeerName();

protected:
    virtual int run();
    virtual void doStop();

    bool checkRead(long ms);

    bool handleCommand();

    void handleClose();

    void closeSocket();

    bool sendPacket(MediaPacketPtr& pkt);

protected:
	UDTSOCKET	m_socket;
    sockaddr_in m_peerAddr;

    std::string m_peerID;
    std::string m_streamName;

    MediaTransportHeader	m_header;
    bool	m_headerReady;
    comn::ByteBuffer m_buffer;

    av::MediaFormat m_format;

    MediaPacketQueue    m_pktQueue;
    std::vector<UDTSOCKET> m_fds;

    //util::UdtSocketPair	m_socketPair;
    UmsgMediaCasterServer*	m_server;

};


} /* namespace av */

#endif /* UMSGMEDIACASTERCONNECTION_H_ */
